/*
 * @Author: WangLi
 * @Date: 2024-03-05 22:02:39
 * @LastEditors: WangLi
 * @LastEditTime: 2024-05-19 07:41:42
 */
import WPage from "../../common/WPage";
import { guid } from "../../utils/util";
import { getUuid, writeBLECharacteristicValue, writeBLECharacteristicValueByDevice } from "../../utils/common";
import { getUser, getDevice, getLastConnectedDevice } from "../../utils/storage";

const app = getApp();
WPage({
  data: {
    title: "首页",
    list: [],
    bluetoothShow: false,
    openid: "",
    connected: false,
    deviceId: "",
  },
  onLoad(options) {
    this.init();
  },
  onShow() {
    this.init();
  },
  onUnload() {
    this.setData({
      deviceId: "",
    });
  },
  init() {
    const userInfo = getUser();
    this.setData({
      openid: userInfo?.openid,
    });
    this.getListData();
    this.openBluetoothAdapter();
  },
  getListData() {
    const deviceList = getDevice();
    const listData = deviceList.map((item) => ({ ...item, id: guid() }));
    console.log(listData);
    //  [
    //   { id: guid(), name: "设备1", owner: "拥有者", lockStatus: "0", uuid: 1 },
    //   { id: guid(), name: "设备2", owner: "拥有者", lockStatus: "0", uuid: 2 },
    // ];
    this.setData({ list: listData });
  },
  onSearchBluetooth() {
    this.setData({ bluetoothShow: true });
  },
  onPopupClose() {
    this.setData({ bluetoothShow: false });
  },
  goBluetooth() {
    wx.navigateTo({ url: "/pages/bluetooth/index" });
  },
  async goFunctions(e) {
    const { deviceid } = e.currentTarget.dataset;
    const deviceDta = this.data.list.find((item) => item.deviceId === deviceid);
    await this._createBLEConnection(deviceDta, true);
    wx.navigateTo({ url: "/pages/functions/index" });
  },
  async handleUnclock(e) {
    const { deviceid } = e.currentTarget.dataset;
    const deviceDta = this.data.list.find((item) => item.deviceId === deviceid);
    await this._createBLEConnection(deviceDta, true);
    const serviceId = getUuid("5508");
    writeBLECharacteristicValueByDevice(deviceid, serviceId, getUuid("0080"), "", "开锁");
  },
  async handleLock(e) {
    const { deviceid } = e.currentTarget.dataset;
    const deviceDta = this.data.list.find((item) => item.deviceId === deviceid);
    await this._createBLEConnection(deviceDta, true);
    const serviceId = getUuid("5508");
    writeBLECharacteristicValueByDevice(deviceid, serviceId, getUuid("0081"), "", "关锁");
  },
  async handleShare(e) {
    const { deviceid } = e.currentTarget.dataset;
    const deviceDta = this.data.list.find((item) => item.deviceId === deviceid);
    await this._createBLEConnection(deviceDta, true);
    const serviceId = getUuid("5508");
    writeBLECharacteristicValueByDevice(deviceid, serviceId, getUuid("0082"), "", "分享");
  },
  createBLEConnectionLastDevice() {
    const lastConnectedDevice = getLastConnectedDevice();
    console.log(lastConnectedDevice, lastConnectedDevice?.deviceId);
    if (lastConnectedDevice?.deviceId) {
      this._createBLEConnection(lastConnectedDevice);
    }
  },
  _createBLEConnection(data, isAction) {
    return new Promise((resolve, reject) => {
      const { deviceId, name } = data;
      console.log(app.globalData.deviceId, deviceId);
      if (app.globalData.deviceId === deviceId) {
        wx.getConnectedBluetoothDevices({
          success(res) {
            console.log(res);
          },
          fail(res) {
            console.log(res);
          },
        });
        resolve();
        return;
      }
      if (isAction) {
        wx.showLoading({
          title: "连接中...",
        });
      }
      wx.createBLEConnection({
        deviceId,
        success: () => {
          console.log("createBLEConnection success");
          wx.hideLoading();
          // wx.showToast({
          //   title: `蓝牙设备“${name}”连接成功`,
          //   icon: "none",
          //   duration: 2000,
          // });

          app.globalData.deviceId = deviceId;
          this.setData({
            connected: true,
            deviceId,
          });
          this.checkUser();
          resolve();
        },
        fail: (res) => {
          if (res.errCode === -1) {
            app.globalData.deviceId = deviceId;
            resolve();
            return;
          }
          app.globalData.deviceId = "";
          this.setData({
            deviceId: "",
          });
          console.log("createBLEConnection fail", res);
          wx.hideLoading();
          if (isAction) {
            wx.showModal({
              title: "连接不成功",
              content: `请确定“${name}”已打开而且在通信范围内`,
              showCancel: false,
              confirmText: "好",
              success() {
                reject();
              },
            });
          }
        },
      });
    });
  },
  openBluetoothAdapter() {
    wx.openBluetoothAdapter({
      success: (res) => {
        console.log("openBluetoothAdapter success", res);
        wx.getConnectedBluetoothDevices({
          success(res) {
            console.log(res);
          },
          fail: (res) => {
            console.log(res);
          },
        });
        // this.createBLEConnectionLastDevice();
      },
      fail: (res) => {
        console.log("openBluetoothAdapter fail", res);
        if (res.errCode === 10001) {
          wx.showModal({
            title: "连接不成功",
            content: `请确定手机蓝牙已打开`,
            showCancel: false,
            confirmText: "好",
            success() {},
          });
          wx.onBluetoothAdapterStateChange((res) => {
            console.log("onBluetoothAdapterStateChange", res);
            if (res.available) {
              // 取消监听，否则stopBluetoothDevicesDiscovery后仍会继续触发onBluetoothAdapterStateChange，
              // 导致再次调用startBluetoothDevicesDiscovery
              wx.onBluetoothAdapterStateChange(() => {});
            }
          });
        }
      },
    });
  },
  onBLEConnectionStateChange() {
    wx.onBLEConnectionStateChange((res) => {
      // 该方法回调中可以用于处理连接意外断开等异常情况
      console.log("onBLEConnectionStateChange", `device ${res.deviceId} state has changed, connected: ${res.connected}`);
      if (res.deviceId === this.data.deviceId) {
        if (!res.connected) {
          app.globalData.deviceId = "";
          this.setData({
            deviceId: "",
          });
          const deviceDta = this.data.list.find((item) => item.deviceId === res.deviceId);
          wx.showModal({
            title: "连接不成功",
            content: `蓝牙设备“${deviceDta.name}”连接已断开`,
            showCancel: false,
            confirmText: "好",
          });
        }
      }
    });
  },
  checkUser() {
    const userInfo = getUser();
    const { openid } = userInfo;
    const serviceId = getUuid("5508");
    writeBLECharacteristicValue(serviceId, getUuid("0083"), openid);
  },
});
